package com.guomei.controller;

import com.guomei.bean.curse.CourseVideo;
import com.guomei.configs.AliyunOssConfig;
import com.guomei.service.AliyunOssService;
import com.guomei.service.utilService.VideoTranscodeService;
import com.guomei.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;



/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/api1/file")
@Slf4j
public class OssController {
    @Autowired
    private AliyunOssService aliyunOssService;

    @Autowired
    private AliyunOssConfig aliyunOssConfig;

    @Autowired
    private VideoTranscodeService transcodeService;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        // 检查文件大小
        if (file.getSize() > aliyunOssConfig.getMaxSize()) {
            return Result.error("文件大小不能超过" + aliyunOssConfig.getMaxSize() / 1024 / 1024 + "MB");
        }

        // 检查文件是否为空
        if (file.isEmpty()) {
            return Result.error("文件不能为空");
        }

        // 上传文件到OSS
        String fileUrl = aliyunOssService.uploadFile(file);

        return Result.success(fileUrl);
    }

    /**
     * 视频上传并转码为多分辨率M3U8
     */
    @PostMapping("/video/upload")
    public Result<?> uploadVideo(@RequestParam("file") MultipartFile file) {

        try {
            // 检查文件大小
            if (file.getSize() > aliyunOssConfig.getMaxSize()) {
                return Result.error("文件大小不能超过" + aliyunOssConfig.getMaxSize() / 1024 / 1024 + "MB");
            }

            // 检查文件是否为空
            if (file.isEmpty()) {
                return Result.error("文件不能为空");
            }
            // 处理视频并获取各分辨率播放地址
            Map<String, String> resolutionUrls = transcodeService.processVideo(file);

            return Result.success(resolutionUrls);
        } catch (Exception e) {
            log.info("视频处理失败：" + e.getMessage());
            return Result.error("视频处理失败");
        }
    }
    @PostMapping("/oss/upload")
    @ResponseBody
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file,@RequestBody CourseVideo courseVideo) {
        Map<String, Object> result = new HashMap<>();
        log.info("上传文件开始,请求体入参->{}",courseVideo);
        if (courseVideo == null || courseVideo.getVideoName() == null ||
        courseVideo.getCourseId() == null || courseVideo.getChapterId() == null
        || courseVideo.getIsFree() == null || courseVideo.getDuration() == null  ||
                courseVideo.getSortOrder() == null) {
            result.put("code", 200);
            result.put("msg", "缺少参数错误");
            return result;
        }
        try {
            // 生成OSS存储路径（如"video/20250101/test_12345.mp4"，避免重名）
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String ossObjectKey = "video/" + System.currentTimeMillis() + suffix;

            // 调用分片上传方法
            return transcodeService.handleUploadRequest(file, ossObjectKey, courseVideo);

        } catch (Exception e) {
            result.put("code", 200);
            result.put("msg", "上传失败：" + e.getMessage());
            return result;
        }
    }

    @GetMapping("/upload/result/{uploadId}")
    public ResponseEntity<Map<String, Object>> queryUploadResult(@PathVariable String uploadId) {
        Map<String, Object> response = new HashMap<>();

        try {
            String result = transcodeService.queryUploadResult(uploadId);

            if (result == null) {
                response.put("code", 200);
                response.put("msg", "未找到上传记录或记录已过期");
                return ResponseEntity.ok(response);
            }

            response.put("code", 200);
            response.put("msg", "查询成功");
            response.put("data", result);

            // 判断上传状态
            if (result.startsWith("http")) {
                response.put("status", "completed");
            } else if (result.contains("上传中")) {
                response.put("status", "processing");
            } else if (result.contains("失败")) {
                response.put("status", "failed");
            } else {
                response.put("status", "unknown");
            }

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("查询上传结果失败, uploadId: {}", uploadId, e);
            response.put("code", 500);
            response.put("msg", "查询失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    /**
     * 删除文件
     */
    @DeleteMapping("/delete")
    public Result<String> deleteFile(@RequestParam("fileUrl") String fileUrl) {
        boolean isDeleted = aliyunOssService.deleteFile(fileUrl);

        if (isDeleted) {
            return Result.success("文件删除成功");
        } else {
            return Result.error("文件删除失败");
        }
    }
}
